#include "include/gittool.h"
#include "ui_gittool.h"

GitTool::GitTool(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::GitTool)
{
    ui->setupUi(this);
    setWindowTitle("git工具助手");
    process = new QProcess();
    ui->lineEdit->setReadOnly(true);
    ui->lineEdit_2->setText("master");
    ui->pushButton_6->setToolTip("帮助");
}

GitTool::~GitTool()
{
    delete ui;
}

void GitTool::Clone(){
    gitInit = new GitInit();
    connect(gitInit,&GitInit::ToUrl,this,[&](QString Url){
        this->Url=Url;
    });
    gitInit->show();
}

void GitTool::AddDate(){
    QDateTime currentDateTime = QDateTime::currentDateTime(); // 获取当前日期和时间
    // 使用默认格式（ISO 8601）
    QString dateTimeStr = currentDateTime.toString();

    // 使用自定义格式
    QString customDateTimeStr = currentDateTime.toString("yyyy-MM-dd HH:mm:ss");
    // 设置红色字体格式
    QTextCharFormat redFormat;
    redFormat.setForeground(Qt::red);
    ui->textBrowser->setCurrentCharFormat(redFormat);
    ui->textBrowser->append(customDateTimeStr);
    redFormat.setForeground(Qt::black);
    ui->textBrowser->setCurrentCharFormat(redFormat);
}

void GitTool::AddOutPut(){
    // 获取进程的输出
    output=process->readAllStandardOutput();;
    error=process->readAllStandardError();
    data = output!=""?output:error;
    ui->textBrowser->append(data);
}

void GitTool::on_pushButton_clicked()
{
    // 打开一个文件夹选择对话框
    directory = QFileDialog::getExistingDirectory(
       nullptr,                  // 父窗口
       "选择文件夹",            // 对话框标题
       "C:/",                       // 初始路径
       QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks // 仅显示文件夹
    );
    ui->lineEdit->setText(directory);
    ui->label->setAlignment(Qt::AlignCenter);
    process->setWorkingDirectory(directory);
}

void GitTool::on_pushButton_2_clicked()
{
    if(directory==""){
        QMessageBox::warning(this, "警告", "文件夹路径错误！", QMessageBox::Ok);
        return;
    }
    // 设置鼠标光标为等待类型
    QApplication::setOverrideCursor(Qt::WaitCursor);
    AddDate();
    /*1*/
    process->start("git add .");
    process->waitForFinished();
    AddOutPut();
    if(data=="fatal: not a git repository (or any of the parent directories): .git\n"){
        // 恢复鼠标光标
        QApplication::restoreOverrideCursor();
        gitInit = new GitInit(directory,false);
        gitInit->exec();
        return;
    }
    /*2*/
    process->start(tr("git commit -m \"%1\"")
                   .arg(ui->textEdit->toPlainText()!=""?ui->textEdit->toPlainText():"日常代码提交"));
    process->waitForFinished();
    AddOutPut();
    /*3*/
    process->start("git pull origin master");
    process->waitForFinished();
    AddOutPut();
    /*4*/
    process->start("git push origin master -f");
    process->waitForFinished();
    AddOutPut();
    // 恢复鼠标光标
    QApplication::restoreOverrideCursor();
    if(data=="Everything up-to-date\n"){
        QMessageBox::warning(this, "警告", "当前文件没有更新文件！", QMessageBox::Ok);
    }else if(data.contains("error")){
        QMessageBox::critical(this, "提交失败",data , QMessageBox::Ok);
    }

}

void GitTool::on_pushButton_4_clicked()
{
    if(directory==""){
        QMessageBox::warning(this, "警告", "文件夹路径错误！", QMessageBox::Ok);
        return;
    }
    /*1*/
    process->start("git status");
    process->waitForFinished();
    // 获取进程的输出
    output=process->readAllStandardOutput();;
    error=process->readAllStandardError();
    data = output!=""?output:error;
    if(data=="fatal: not a git repository (or any of the parent directories): .git\n"){
        QMessageBox messageBox(QMessageBox::Warning,"警告", "该文件夹非Git仓库，是否将文件拉取在此？",QMessageBox::Yes|QMessageBox::No,NULL);
        if(messageBox.exec()==QMessageBox::Yes){
            Clone();
            if(this->Url=="")return;
            AddDate();
            process->start(tr("git clone %1").arg(this->Url));
            process->waitForFinished();
            AddOutPut();
        }
        return;
    }
    // 设置鼠标光标为等待类型
    QApplication::setOverrideCursor(Qt::WaitCursor);
    AddDate();
    /*2*/
    process->start(tr("git fetch origin %1").arg(ui->lineEdit_2->text()));
    process->waitForFinished();
    AddOutPut();
    /*3*/
    process->start(tr("git log -p master.. origin/%1").arg(ui->lineEdit_2->text()));
    process->waitForFinished();
    AddOutPut();
    // 恢复鼠标光标
    QApplication::restoreOverrideCursor();
}

void GitTool::on_pushButton_5_clicked()
{
    if(directory==""){
        QMessageBox::warning(this, "警告", "文件夹路径错误！", QMessageBox::Ok);
        return;
    }
    QMessageBox messageBox(QMessageBox::Question,"提示", "是否将远程仓库与本地仓库合并？",QMessageBox::Yes|QMessageBox::No,NULL);
    if(messageBox.exec()==QMessageBox::No)return;
    /*1*/
    process->start(tr("git merge origin/%1").arg(ui->lineEdit_2->text()));
    process->waitForFinished();
    AddDate();
    AddOutPut();
    if(data=="Already up to date.\n"){
        QMessageBox::warning(this, "警告", "本地分支已经与远程仓库的对应分支同步，没有新的提交可供更新!", QMessageBox::Ok);
    }else if(data=="fatal: not a git repository (or any of the parent directories): .git\n"){
        QMessageBox::warning(this, "警告", "该文件夹没有仓库！", QMessageBox::Ok);
    }
}

void GitTool::on_pushButton_3_clicked()
{
    if(directory==""){
        QMessageBox::warning(this, "警告", "文件夹路径错误！", QMessageBox::Ok);
        return;
    }
    gitInit = new GitInit(directory,true);
    connect(gitInit,&GitInit::ToUrl,this,[&](QString branch){
        ui->lineEdit_2->setText(branch);
    });
    gitInit->exec();
    AddDate();
    process->start(tr("git checkout -b %1").arg(ui->lineEdit->text()));
    process->waitForFinished();
    AddOutPut();
    if(data.contains("fatal:")){
        QMessageBox messageBox(QMessageBox::Question,"警告", "已存在该分支，是否切换到此分支？",QMessageBox::Yes|QMessageBox::No,NULL);
        if(messageBox.exec()==QMessageBox::Yes){
            process->start(tr("git switch %1").arg(ui->lineEdit->text()));
            process->waitForFinished();
            AddOutPut();
        }
    }
    QMessageBox::information(this,"提示", "创建成功！",QMessageBox::Yes);
}

void GitTool::on_pushButton_6_clicked()
{
    // 要打开的网址
    QUrl url("https://gitee.com/zhoudawei666/git-tool.git"); // 替换为你想要的网页
    QDesktopServices::openUrl(url);
}
